﻿using System;
using System.Collections.Generic;
using System.Text;
using RegionInterface;
using Common;
using UnityEngine;
using System.Threading;
public class NetworkModule : ModuleBase, INetworkModule
{
    private Dictionary<ModuleType, INetwork> moduleList = new Dictionary<ModuleType, INetwork>();
    public RegionContion RegionHandle;
    public NetworkModule()
    {
        RegionHandle = new RegionContion(this);
        AppInterface.NetworkModule = this as INetworkModule;
    }
    public override void OnGUI()
    {

    }
    public override void Update()
    {
        RegionHandle.Update();
    }
    public override void FixedUpdate()
    {
        RegionHandle.FixedUpdate();
    }
    public void Close()
    {
        RegionHandle.Close();
    }
    public void OnMessage(ServerType server, DataObject msg)
    {
        //switch (Msg.ReadByte())
        //{
        //    case GameMessageType.REGION_CHAT:
        //        {
        //            Msg.Reset();
        //            Module.Game.CGUIModule.OnNetMessage(Msg);
        //            break;
        //        }
        //    default:
        //        {
        //            Msg.Reset();
        //            Module.Game.CAvatarModule.OnNetMessage(Msg);
        //            break;
        //        }
        //}
        foreach (KeyValuePair<ModuleType, INetwork> mod in moduleList)
        {
            mod.Value.OnNetMessage(server, msg);
        }
    }
    #region INetworkModule Members

    public void RegisterNetworkHandle(INetwork module)
    {
        moduleList[module.Type] = module;
    }

    public void SendNetworkMessage(ServerType server, Action<DataObject> messageHandle)
    {
        if (server == ServerType.RegionServer)
        {
            if (Define.NoNetwork || RegionHandle.Client == null) return;
            DataObject msg = RegionHandle.Client.client.BufferPool.Get();
            messageHandle(msg);
            RegionHandle.Client.SendMessage(msg);
            RegionHandle.Client.client.BufferPool.Put(msg);
        }
    }

    public void OpenServer(ServerType server, string serverIp, int port, int background, string doMain)
    {
        if (server == ServerType.RegionServer)
        {
            RegionHandle.Init(serverIp, port, background, doMain);
        }
    }

    public void PlayerLogin(ServerType server, int id, string name, string para)
    {
        if (server == ServerType.RegionServer)
        {
            RegionHandle.Login(id, name, para);
        }
    }

    public void CloseServer(ServerType server)
    {
        if (server == ServerType.RegionServer)
        {
            RegionHandle.Close();
        }
    }

    public void GetRegionPlayers()
    {
        RegionHandle.RequestPlayers();
    }

    public void GetRegionNextPlayer()
    {
         RegionHandle.Client.GetNextPlayer();
    }

    #endregion
}